<template>
   <mySelect v-bind="$attrs" @input="$emit('input',$event)" :filterMethod="filter" :value-key="valueKey" :label-key="labelKey" v-selectScroll="handleScroll">
    <el-option
        v-for="item in dataList"
        :key="item[valueKey]"
        :label="item[labelKey]"
        :value="item">
    </el-option>
   </mySelect>
</template>

<script>
  export default{
    name:'selectScroll',
    props:{
      filterMethod:{
        type:Function,
        required:true
      },
      valueKey: {
        type: String,
        default: 'value'
      },
      labelKey: {
        type: String,
        default: 'label'
      },
      queryKey:{
        type:String,
        default:'name'
      },
      deft: {
        type: Object,
        default: () => {}
      }
    },
    data(){
      return{
        dataList:[],
        pageNum:1,
        pageSize:10,
        queryStr:'',
        finish:false,
        loading:false
      }
    },
    created(){
      this.init()
    },
    methods:{
      init(){
        this.filter('')
      },
      handleScroll(down){
        if(down && !this.finish && !this.loading){
          this.loading = true
          this.req().then(res=>{
            let item,temp;
            for(let i=0;i<res.rows.length;i++){
              item = res.rows[i]
              temp = this.dataList.find(t=>t[this.valueKey] == item[this.valueKey])
              if(!temp){
                this.dataList.push(item)
              }
              if(this.dataList.length >= res.total){
                this.finish = true
              }
            }
            this.loading = false
          })
        }
      },
      filter(e){
        this.pageNum = 1
        this.queryStr = e
        this.finish = false
        this.req().then(res=>{
          this.dataList = res.rows
        })
      },
      req(){
        let queryParams = {
          pageNum:this.pageNum,pageSize:this.pageSize
        }
        queryParams[this.queryKey] = this.queryStr
        return new Promise((q,j)=>{
          this.filterMethod(queryParams).then(res=>{
            this.pageNum++
            q(res)
          })
        })
      }
    },
    watch: {
      'deft.entrustOrganizationId': {
        handler(val) {
          if (!this.deft || !this.deft.entrustOrganizationId) return
          const findRes = this.dataList.find(item => item.entrustOrganizationId === this.deft.entrustOrganizationId)
          if (!findRes) this.dataList.unshift(this.deft)
        },
        deep: true
      }
    }
  }
</script>

<style>
</style>
